package com.hackathon.chgk.taskloaders.impl;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.nodes.Element;

import android.util.Log;

import com.hackathon.chgk.ChgkApplication;
import com.hackathon.chgk.data.DatabaseHelper;
import com.hackathon.chgk.data.dao.Task;
import com.hackathon.chgk.taskloaders.TaskLoader;
import com.hackathon.chgk.utils.HtmlHelper;

public class OnlineTaskLoaderImpl implements TaskLoader {

	private URL url;
	private HtmlHelper htmlHelper;
	
	static final String CLASSNAME = OnlineTaskLoaderImpl.class.getName();

	public OnlineTaskLoaderImpl(URL url) {

		this.url = url;		
	}
	
	public Task getRandomTask() {
		// TODO Auto-generated method stub
		return null;
	}

	public List<Task> getRandomTasks(int count) throws Exception {
		
		List<Task> results = new ArrayList<Task>();			
		
		try {				
			
			while (results.size() < count) {	
				
				List<Element> tasks = this.createNewHtmlHelper()
						.getQuestionsByClass("random_question");

				for (Element node : tasks) {					
					results.add(this.getHtmlHelper()
							.getTaskByTagNode(node));
				}
			}
		}
		catch (Exception e) {

			Log.e(CLASSNAME,"Cannot parse page");
			e.printStackTrace();
		}	
		if (results.size() > 0) {
			try {
				DatabaseHelper dbHelper = new DatabaseHelper(ChgkApplication.getInstance().getCurrentContext());
				dbHelper.createTasks(results);
				results = results.subList(0, count);
			}
			catch (Exception e) {
				
				Log.e(CLASSNAME,"Cannot save data to db");
				e.printStackTrace();
				throw e;
			}
		}
		return results;
	}

	public HtmlHelper getHtmlHelper() throws IOException {
		
		if(htmlHelper == null) {
			
			this.htmlHelper = createNewHtmlHelper();				
		}
		return htmlHelper;
	}
	
	public HtmlHelper createNewHtmlHelper() throws IOException {
		
		HtmlHelper hh = null;
		try {
			
			hh = new HtmlHelper(this.url);
		}
		catch (IOException e) {

			Log.e(CLASSNAME,"Cannot create HtmlHelper");
			e.printStackTrace();
			throw e;
		}	
		return hh;
	}

	public void setHtmlHelper(HtmlHelper htmlHelper) {
		this.htmlHelper = htmlHelper;
	}

}
